/**
 * 后端兼容性检查脚本
 * 用于验证后端API是否与前端期望的接口格式匹配
 */

import axios from 'axios';

// 配置
const BASE_URL = 'http://localhost:3000/api';
const TEST_USER = {
  username: 'testuser',
  password: 'testpass123',
  email: 'test@example.com'
};

// 颜色输出
const colors = {
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  reset: '\x1b[0m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

// 测试用例
const tests = [
  {
    name: '检查服务器是否运行',
    test: async () => {
      try {
        const response = await axios.get(`${BASE_URL.replace('/api', '')}/health`);
        return { success: true, message: '服务器运行正常' };
      } catch (error) {
        return { success: false, message: `服务器连接失败: ${error.message}` };
      }
    }
  },
  {
    name: '测试登录接口格式',
    test: async () => {
      try {
        const response = await axios.post(`${BASE_URL}/auth/login`, {
          username: 'admin',
          password: 'admin123'
        });
        
        const data = response.data;
        
        // 检查响应格式
        if (typeof data.code !== 'number') {
          return { success: false, message: '响应缺少 code 字段或格式错误' };
        }
        
        if (!data.data || !data.data.token) {
          return { success: false, message: '响应缺少 token 字段' };
        }
        
        return { 
          success: true, 
          message: '登录接口格式正确',
          data: { token: data.data.token }
        };
      } catch (error) {
        if (error.response) {
          return { 
            success: false, 
            message: `登录失败: ${error.response.status} - ${error.response.data?.message || error.message}` 
          };
        }
        return { success: false, message: `登录接口连接失败: ${error.message}` };
      }
    }
  },
  {
    name: '测试获取用户信息接口',
    test: async (context) => {
      if (!context.token) {
        return { success: false, message: '需要先登录获取 token' };
      }
      
      try {
        const response = await axios.get(`${BASE_URL}/auth/me`, {
          headers: { Authorization: `Bearer ${context.token}` }
        });
        
        const data = response.data;
        const user = data.data;
        
        // 检查必需字段
        const requiredFields = ['id', 'username'];
        const missingFields = requiredFields.filter(field => !user[field]);
        
        if (missingFields.length > 0) {
          return { 
            success: false, 
            message: `用户信息缺少必需字段: ${missingFields.join(', ')}` 
          };
        }
        
        // 检查可选但推荐的字段
        const recommendedFields = ['email', 'roles', 'createdAt', 'updatedAt'];
        const missingRecommended = recommendedFields.filter(field => !user[field]);
        
        let message = '用户信息接口格式正确';
        if (missingRecommended.length > 0) {
          message += `，但建议添加字段: ${missingRecommended.join(', ')}`;
        }
        
        return { success: true, message, data: user };
      } catch (error) {
        return { 
          success: false, 
          message: `获取用户信息失败: ${error.response?.status} - ${error.response?.data?.message || error.message}` 
        };
      }
    }
  },
  {
    name: '测试用户列表接口',
    test: async (context) => {
      if (!context.token) {
        return { success: false, message: '需要先登录获取 token' };
      }
      
      try {
        const response = await axios.get(`${BASE_URL}/users?page=1&limit=10`, {
          headers: { Authorization: `Bearer ${context.token}` }
        });
        
        const data = response.data;
        const result = data.data;
        
        // 检查分页格式
        if (!Array.isArray(result.data)) {
          return { success: false, message: '用户列表应该包含 data 数组' };
        }
        
        const requiredPaginationFields = ['total', 'currentPage', 'perPage'];
        const missingPagination = requiredPaginationFields.filter(field => 
          typeof result[field] !== 'number'
        );
        
        if (missingPagination.length > 0) {
          return { 
            success: false, 
            message: `分页信息缺少字段: ${missingPagination.join(', ')}` 
          };
        }
        
        return { 
          success: true, 
          message: `用户列表接口格式正确，共 ${result.total} 个用户` 
        };
      } catch (error) {
        return { 
          success: false, 
          message: `获取用户列表失败: ${error.response?.status} - ${error.response?.data?.message || error.message}` 
        };
      }
    }
  },
  {
    name: '测试搜索功能',
    test: async (context) => {
      if (!context.token) {
        return { success: false, message: '需要先登录获取 token' };
      }
      
      try {
        const response = await axios.get(`${BASE_URL}/users?search=admin`, {
          headers: { Authorization: `Bearer ${context.token}` }
        });
        
        return { success: true, message: '搜索功能正常' };
      } catch (error) {
        return { 
          success: false, 
          message: `搜索功能测试失败: ${error.response?.status} - ${error.response?.data?.message || error.message}` 
        };
      }
    }
  }
];

// 运行测试
async function runTests() {
  log('🔍 开始检查前后端兼容性...', 'blue');
  log('='.repeat(50), 'blue');
  
  const context = {};
  let passedTests = 0;
  
  for (const test of tests) {
    log(`\n📋 ${test.name}`, 'yellow');
    
    try {
      const result = await test.test(context);
      
      if (result.success) {
        log(`✅ ${result.message}`, 'green');
        passedTests++;
        
        // 保存测试结果到上下文
        if (result.data?.token) {
          context.token = result.data.token;
        }
      } else {
        log(`❌ ${result.message}`, 'red');
      }
    } catch (error) {
      log(`❌ 测试执行出错: ${error.message}`, 'red');
    }
  }
  
  log('\n' + '='.repeat(50), 'blue');
  log(`📊 测试结果: ${passedTests}/${tests.length} 通过`, passedTests === tests.length ? 'green' : 'yellow');
  
  if (passedTests === tests.length) {
    log('🎉 所有测试通过！前后端接口兼容性良好。', 'green');
  } else {
    log('⚠️  存在兼容性问题，请检查后端实现。', 'yellow');
    log('\n💡 建议:', 'blue');
    log('1. 确保后端按照 docs/backend-api-spec.md 规范实现', 'blue');
    log('2. 检查数据库表结构是否包含所有必需字段', 'blue');
    log('3. 验证响应格式是否符合前端期望', 'blue');
  }
}

// 错误处理
process.on('unhandledRejection', (error) => {
  log(`❌ 未处理的错误: ${error.message}`, 'red');
  process.exit(1);
});

// 运行测试
runTests().catch(error => {
  log(`❌ 测试运行失败: ${error.message}`, 'red');
  process.exit(1);
});